<template>
  <div class="page">
    <global-header @back="$router.back()">
      <template #title>
        <div class="flex items-center" @click="state.show = !state.show">
          <span class="text-[17px] mr-[5px]">{{ tabName }}</span>
          <span class="arrow" :class="{ rotate: state.show }">
            <svg-icon name="title-arrow" />
          </span>
        </div>
      </template>
      <template #right>
        <div class="text-[15px] mr-[10px]" @click="handleAllReset">消息重置</div>
      </template>
    </global-header>
    <main class="page-main relative flex flex-col justify-between">
      <transition name="fade">
        <div v-if="state.show" class="fliter-mark" @click="state.show = false"></div>
      </transition>
      <transition name="down">
        <div v-if="state.show" class="fliter-main">
          <div class="grid grid-cols-3 gap-x-[8px] gap-y-[10px] px-[16px] py-[10px]">
            <div
              class="filter-item"
              v-for="(item, index) in gameTotal"
              :class="{
                active: index == state.tabActive
              }"
              @click="handleActive(index)"
            >
              <span>{{ item.Name }}</span>
            </div>
          </div>
        </div>
      </transition>
      <div class="page-main overflow-y-auto">
        <loading v-if="state.loading" />
        <van-collapse v-else v-model="state.activeNames">
          <van-collapse-item :title="item.Key" :name="item.Key" v-for="item in state.messages">
            <div>
              <div class="text-[12px]">
                注意：所有花括号（比如{游戏}）包含的都属于系统内置识别码，请不要更改，否则会导致系统无法识别指令。
              </div>
              <section class="mb-[10px]" v-if="item.TimeEdit == 1">
                <div class="label-title">时间</div>
                <div class="field-box flex items-center">
                  <van-field v-model="item.Time" type="digit" label="距封盘">
                    <template #right-icon> 秒 </template>
                  </van-field>
                </div>
              </section>
              <section class="mb-[10px]">
                <div class="label-title">内容</div>
                <div class="textfield-box flex items-center">
                  <van-field v-model="item.Content" type="textarea" rows="5"> </van-field>
                </div>
              </section>
              <section class="mb-[10px]" v-if="showDescribe(item.Key)">
                <div class="label-title">说明</div>
                <div class="border !border-[#ccc] rounded-[8px] p-[15px] bg-[#fff]">
                  <template v-if="item.Key == '距封盘N秒喊话'">
                    <div>
                      <div>{游戏}游戏名称</div>
                      <div>{期号}表示当期期号</div>
                      <div>{second}表示消息时间设置的具体秒</div>
                    </div>
                  </template>
                  <template v-if="item.Key == '封盘后账单核对消息'">
                    <div>
                      <div>{核对}以玩家为单位，对订单进行汇总核对</div>
                    </div>
                  </template>
                  <template v-if="item.Key == '结算后中奖名单'">
                    <div>
                      <div>{结算} 以玩家为单位，对结算订单展示</div>
                      <div>{中奖名单} 以玩家为单位，对玩家中奖订单展示</div>
                    </div>
                  </template>
                  <template v-if="item.Key == '结算后玩家积分消息'">
                    <div>
                      <div>{账单} 以玩家为单位，展示投注玩家的积分情况</div>
                      <div>{玩家数量} 表示有下注的玩家人数</div>
                    </div>
                  </template>
                </div>
              </section>
            </div>
          </van-collapse-item>
        </van-collapse>
        <div class="h-[10px]"></div>
      </div>
      <div class="mx-[15px] py-[10px]">
        <van-button
          block
          round
          :loading="state.updating"
          :disabled="state.updating"
          :loading-text="state.updating ? '保存中...' : ''"
          type="primary"
          @click="handleSave"
          >保存设置</van-button
        >
      </div>
    </main>
  </div>
</template>
<route>
  {
    name: "admin-setting-message",
    meta: {
      pageIndex: 3,
    }
  }
</route>
<script setup lang="ts">
import { reqMessageDefault, reqMessageEdit, reqMessageShow } from "@/api/setting";
import { useGameStore } from "@/store/modules/game";
import { usePremsStore } from "@/store/modules/prems";
import { toast } from "@/utils/toast";
import { cloneDeep, debounce } from "lodash-es";
import { storeToRefs } from "pinia";

const premsStore = usePremsStore();
const gameStore = useGameStore();
const { gameTotal } = storeToRefs(gameStore);
const state = reactive({
  show: false,
  loading: false,
  updating: false,
  msgId: 0,
  messages: <MessageSettingTables[]>[],
  cloneMessages: <MessageSettingTables[]>[],
  tabActive: 0,
  activeNames: []
});
const tabName = computed(() => {
  return gameTotal.value[state.tabActive].Name;
});
const tabId = computed(() => {
  return gameTotal.value[state.tabActive].LotteryId;
});

const showDescribe = (key: string) => {
  if (
    key == "距封盘N秒喊话" ||
    key == "封盘后账单核对消息" ||
    key == "结算后中奖名单" ||
    key == "结算后玩家积分消息"
  ) {
    return true;
  }
  return false;
};

const handleActive = (index: number) => {
  state.tabActive = index;
  state.show = false;
  state.activeNames = [];
  state.messages = cloneDeep([]);
  nextTick(() => {
    getData();
  });
};

// 获取消息
const getData = async () => {
  try {
    state.loading = true;
    const res = await reqMessageShow(tabId.value);
    state.loading = false;
    state.messages = cloneDeep(res.data.Tables);
    state.msgId = res.data.Id;
    state.cloneMessages = cloneDeep(res.data.Tables);
  } catch (error) {
    state.loading = false;
    state.messages = cloneDeep([]);
    console.log(error);
  }
};

// 保存消息
const handleSave = debounce(
  async () => {
    if (!premsStore.isEditMessageSetting) {
      toast.info("暂无权限");
      return;
    }
    if (JSON.stringify(state.messages) == JSON.stringify(state.cloneMessages)) {
      toast.info("暂无修改");
      return;
    }
    try {
      state.updating = true;
      const query = state.messages.map(item => {
        return {
          Content: item.Content,
          Key: item.Key,
          TimeEdit: item.TimeEdit,
          Time: Number(item.Time)
        };
      });
      await reqMessageEdit({
        Id: state.msgId,
        LotteryId: tabId.value,
        Data: query
      });
      state.updating = false;
      toast.success("保存成功");
    } catch (error) {
      state.updating = false;
      console.log(error);
    }
  },
  300,
  { leading: true, trailing: false }
);

// 一键恢复默认
const handleAllReset = () => {
  if (!premsStore.isEditMessageSetting) {
    toast.info("暂无权限");
    return;
  }
  showConfirmDialog({
    title: "",
    message: "确定要恢复到系统初始消息设置吗？",
    className: "confirm-dialog",
    beforeClose: async (action: string) => {
      return new Promise<boolean>(async resolve => {
        if (action === "confirm") {
          try {
            await reqMessageDefault(tabId.value);
            toast.success("恢复默认成功");
            getData();
            resolve(true);
          } catch (error) {
            resolve(true);
          }
        } else {
          resolve(true);
        }
      });
    }
  });
};

onMounted(() => {
  getData();
});
</script>
<style lang="css" scoped>
.filter-item {
  @apply flex-1 bg-[#ededed] h-[27px] rounded-[27px] flex items-center justify-center text-[#7e7e7e];
}
.filter-item.active {
  @apply bg-[var(--primary)] text-[#fff];
}
.label-title {
  @apply flex items-center border-l-[3px] border-solid !border-[var(--primary)] pl-[10px] my-[10px];
}
</style>
<style lang="scss" scoped>
.field-box {
  .van-field {
    border: 1px solid #ccc;
    border-radius: 8px;
    :deep() {
      .van-field__right-icon {
        color: #111;
        padding-left: 15px;
      }
      .van-field__control {
        text-align: right;
        color: #999;
      }
    }
  }
}
.textfield-box {
  .van-field {
    border: 1px solid #ccc;
    border-radius: 8px;
    :deep() {
      .van-field__control {
        color: #999;
      }
    }
  }
}
.arrow {
  transition: transform 0.3s ease;
  width: 12px;
  height: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.arrow.rotate {
  transform: rotate(180deg);
}
.fliter-main {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  z-index: 10;
}
.fliter-mark {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1;
}
:deep() {
  .van-collapse-item__content {
    background-color: #f8f8f8;
  }
}
</style>
